package com.link.base.base.appduty.controller;

import com.link.base.base.gateway.service.GatewayService;
import com.link.base.base.user.model.User;
import com.link.base.base.appduty.model.AppDuty;
import com.link.base.base.appduty.service.AppDutyService;
import com.link.base.base.common.model.InterObject;
import com.link.base.base.urlinfo.model.UrlInfo;
import com.link.base.base.urlinfo.service.AppUrlDutyLinkService;
import com.link.core.basic.query.Filter;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.RedisUtil;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author unknwon
 * @version 1.0
 * @date: 2018/11/8 13:47
 */

@Controller
@RequestMapping("/link/appduty")
public class AppDutyController extends BasicController<AppDuty> {

    @Resource
    private AppDutyService appDutyService;

    @Resource
    private GatewayService gatewayService;
    @Resource
    private AppUrlDutyLinkService urlDutyLinkService;

    @Override
    public BasicService<AppDuty> getBasicService() throws Exception {
        if (appDutyService != null) {
            return appDutyService;
        }
        throw new ServiceException("PUBLIC-005");
    }

    /**
     * picklist查询000公司帐套信息
     */
    @RequestMapping(value = "/queryStandardPage")
    @ResponseBody
    public Map<String, Object> queryStandardPage(@JsonParam QueryParams qps, @JsonParam AppDuty entity, HttpSession session,
                                                 HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            qps.preDealSecurity(request);
            AppDuty t = (AppDuty) BasicModel.transformClass(entity.getClass(), qps);
            beforQueryAllOrExample(t, request);
            beforQueryExample(t, request);
            t.setLoginCorpId(0L);
            List<AppDuty> list = getBasicService().queryByExamplePage(t);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", getCount((BasicModel) t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<AppDuty>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/dutyOfUserList", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> dutyOfUserList(@JsonParam User record, @JsonParam QueryParams qps, HttpSession session,
                                              HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        List<User> list = null;
        try {
            qps.invokePreFilterAndSorter();
            List<Filter> filterList = qps.getFilterByProperty("dutyId");
            if (filterList == null || filterList.size() == 0) {
                qps.addFilter(new Filter("dutyId", "noMatchId"));
            }
            User t = (User) BasicModel.transformClass(User.class, qps);
            list = appDutyService.queryDutyOfUserListPage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount((BasicModel) t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/addUserOfDuty", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addUserOfDuty(@RequestBody List<InterObject> list, QueryParams qps,
                                             HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            for (int i = 0; list != null && i < list.size(); i++) {
                InterObject record = list.get(i);
                User user = new User();
                user.setDutyId(record.getPreObjId());
                user.setId(record.getRearObjId());
                appDutyService.addUserOfDutyInsert(user);
            }
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/delUserOfDuty", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> delUserOfDuty(@JsonParam InterObject record, @JsonParam QueryParams qps, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            appDutyService.delUserOfDuty(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询未被当前url关联的职责列表
     *
     * @param record 职责
     * @author yaojiangyi
     * @date 2019/02/28 16:53
     */
    @RequestMapping(value = "/unSelectAppDutyOfUrl", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> unSelectAppDutyOfUrl(@JsonParam AppDuty record, @JsonParam QueryParams qps,
                                                    HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        List<AppDuty> list = null;
        try {
            AppDuty t = (AppDuty) BasicModel.transformClass(AppDuty.class, qps);
            list = appDutyService.queryunSelectAppDutyOfUrlPage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount((BasicModel) t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * <p>查询未关联职责的url</p>
     *
     * @param record
     * @param qps
     * @param session
     * @param request
     * @param response
     * @author yrf
     */
    @RequestMapping(value = "/unSelectUrlList", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> unSelecturlList(@JsonParam UrlInfo record, @JsonParam QueryParams qps, HttpSession session,
                                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        List<UrlInfo> list = null;
        try {
            UrlInfo t = (UrlInfo) BasicModel.transformClass(UrlInfo.class, qps);
            t.setType(record.getType());
            list = appDutyService.queryUnSelectUrlListPage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount((BasicModel) t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/unSelectUserList", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> unSelectUserList(@JsonParam User record, @JsonParam QueryParams qps, HttpSession session,
                                                HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        List<User> list = null;
        qps.setAttr1(String.valueOf(record.getId()));
        try {
            User t = (User) BasicModel.transformClass(User.class, qps);
            list = appDutyService.queryUnSelectUserListPage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount((BasicModel) t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 更新redis中APP 的职责与用户以及职责与URL的对应关系
     *
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/updatePermissions")
    @ResponseBody
    public Map<String, Object> updatePermissions(HttpSession session, HttpServletRequest request,
                                                 HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            appDutyService.refreshPermissions();
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 刷新单条职责的权限信息
     *
     * @author 黄龙建
     * @date 2020年07月07日
     */
    @RequestMapping(value = "/refreshPermByDutyId")
    @ResponseBody
    public Map<String, Object> refreshPermByDutyId(@JsonParam AppDuty appDuty, HttpSession session, HttpServletRequest request,
                                                   HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            if (appDuty.getId() == null) {
                throw new Exception("职责ID不能为空！");
            }
            appDutyService.refreshPermByDutyId(appDuty);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * @author HuangLJ
     * @date 2019-07-25 14:09
     * @param dutyList 所有职责的列表
     * @param keyName 要清楚的key的名字
     * @throws Exception 报错
     * 把职责权限中，已经在表中被删掉的key在redis中也删除掉
     */
    private void deleteNoUseDutyFromRedis(List<AppDuty> dutyList, String keyName) throws Exception {
        LinkRedisClient jedis = RedisUtil.getJedis();
        try {
            //把已经被删掉的职责从redis里面清楚
            Set<String> dutyIdRedis = jedis.hkeys(keyName);
            for (String id : dutyIdRedis) {
                for (AppDuty duty : dutyList) {
                    String dutyId = String.valueOf(duty.getId());
                    if (!id.equals(dutyId)) {
                        break;
                    }
                }
                jedis.hdel(keyName, id);
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        } finally {
            RedisUtil.returnResource(jedis);
        }
    }

}
